'use strict';

const Controller = require('egg').Controller;

class StatsController extends Controller {
  // 获取概览统计
  async overview() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1; // 临时使用演示用户ID

    try {
      // 获取衣服数量
      const clothingCount = await ctx.model.Clothing.count({
        where: { user_id: userId },
      });

      // 获取搭配数量
      const outfitCount = await ctx.model.Outfit.count({
        where: { user_id: userId },
      });

      // 获取穿搭记录数量 (使用Sequelize ORM)
      const wearRecordCount = await ctx.model.WearRecord.count({
        where: { user_id: userId }
      });

      // 获取收藏衣服数量
      const favoriteClothingCount = await ctx.model.Clothing.count({
        where: { 
          user_id: userId,
          is_favorite: true,
        },
      });

      // 获取收藏搭配数量
      const favoriteOutfitCount = await ctx.model.Outfit.count({
        where: { 
          user_id: userId,
          is_favorite: true,
        },
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
          clothing_count: clothingCount,
          outfit_count: outfitCount,
          wear_record_count: wearRecordCount,
          favorite_clothing_count: favoriteClothingCount,
          favorite_outfit_count: favoriteOutfitCount,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取衣服统计
  async clothing() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      // 按分类统计
      const categoryStats = await ctx.model.Clothing.findAll({
        where: { user_id: userId },
        attributes: [
          'category_id',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
        ],
        include: [
          {
            model: ctx.model.Category,
            as: 'category',
            attributes: ['name'],
          },
        ],
        group: ['category_id'],
      });

      // 按颜色统计
      const colorStats = await ctx.model.Clothing.findAll({
        where: { 
          user_id: userId,
          color: { [ctx.app.Sequelize.Op.ne]: null },
        },
        attributes: [
          'color',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
        ],
        group: ['color'],
        order: [[ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'DESC']],
      });

      // 按季节统计
      const seasonStats = await ctx.model.Clothing.findAll({
        where: { 
          user_id: userId,
          season: { [ctx.app.Sequelize.Op.ne]: null },
        },
        attributes: [
          'season',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
        ],
        group: ['season'],
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
          category: categoryStats,
          color: colorStats,
          season: seasonStats,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取搭配统计
  async outfit() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      // 按风格统计
      const styleStats = await ctx.model.Outfit.findAll({
        where: { 
          user_id: userId,
          style: { [ctx.app.Sequelize.Op.ne]: null },
        },
        attributes: [
          'style',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
          [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('rating')), 'avg_rating'],
        ],
        group: ['style'],
      });

      // 按季节统计
      const seasonStats = await ctx.model.Outfit.findAll({
        where: { 
          user_id: userId,
          season: { [ctx.app.Sequelize.Op.ne]: null },
        },
        attributes: [
          'season',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
        ],
        group: ['season'],
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
          style: styleStats,
          season: seasonStats,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取穿搭统计
  async wear() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      // 最近7天的穿搭记录
      const sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

      const recentWears = await ctx.model.WearRecord.count({
        where: {
          user_id: userId,
          wear_date: {
            [ctx.app.Sequelize.Op.gte]: sevenDaysAgo,
          },
        },
      });

      // 最常穿的衣服
      const mostWornClothing = await ctx.model.Clothing.findAll({
        where: { user_id: userId },
        order: [['wear_count', 'DESC']],
        limit: 5,
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
          recent_wears: recentWears,
          most_worn_clothing: mostWornClothing,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = StatsController;
